/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.springweb.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pers.lcnap.springweb.example.mapper.UserMapper;

import java.util.Collections;

/**
 * 自定义用户验证
 */
@Service
public class AppUserDetailsService implements UserDetailsService {

    final Logger logger = LoggerFactory.getLogger(AppUserDetailsService.class);


    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        pers.lcnap.springweb.example.bean.User user = userMapper.selectOne(
                new QueryWrapper<pers.lcnap.springweb.example.bean.User>()
                        .eq("name", username)
        );

        if (user == null) {
            logger.info(username + " login failed.");
            throw new UsernameNotFoundException("Username Not Found: " + username);
        }
        logger.info(username + " login succeed.");


        //忽略
        User userDetail = new User(username, user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority(user.getAuthority())));

        return userDetail;
    }


}
